import 'package:flutter/material.dart';
import 'package:flutter_wechat/discover_child_page.dart';

import 'const.dart';
import 'data/friends_data.dart';
import 'index_bar.dart';

class AddressBookPage extends StatefulWidget {
  const AddressBookPage({super.key});

  @override
  _AddressBookPageState createState() {
    return _AddressBookPageState();
  }
}

class _AddressBookPageState extends State<AddressBookPage> {
  final List<Friends> _headerData = [
    Friends(
      imageAssets: 'assets/images/新的朋友.png',
      name: '新的朋友',
      indexLetter: '',
    ),
    Friends(imageAssets: 'assets/images/群聊.png', name: '群聊', indexLetter: '1'),
    Friends(imageAssets: 'assets/images/标签.png', name: '标签', indexLetter: '1'),
    Friends(
      imageAssets: 'assets/images/公众号.png',
      name: '公众号',
      indexLetter: '1',
    ),
  ];
  final List<Friends> _listDatas = [];
  late ScrollController _scrollController;

  //字典，里面放item和高度的对应的数据。
  final Map _groupOffsetMap = {INDEX_WORDS[0]: 0.0, INDEX_WORDS[1]: 0.0};

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
    _listDatas
      ..addAll(datas)
      ..addAll(datas);

    _listDatas.sort(
      (Friends a, Friends b) => a.indexLetter.compareTo(b.indexLetter),
    );
    double _cellHeight = 54.5;
    double _groupHeight = 30.0;

    var _groupOffset = _cellHeight * _headerData.length;
    //进过循环计算，将每一个头的位置算出来。放入字典
    for (int i = 0; i < _listDatas.length; i++) {
      if (i < 1) {
        //第一个cell一定有头！
        _groupOffsetMap.addAll({_listDatas[i].indexLetter: _groupOffset});
        //保存完了再加_groupOffset
        _groupOffset += _cellHeight + _groupHeight;
      } else if (_listDatas[i].indexLetter == _listDatas[i - 1].indexLetter) {
        //不同存，只需要加Cell的高度
        _groupOffset += _cellHeight;
      } else {
        _groupOffsetMap.addAll({_listDatas[i].indexLetter: _groupOffset});
        //保存完了再加_groupOffset
        _groupOffset += _cellHeight + _groupHeight;
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: [
          GestureDetector(
            onTap: () {
              Navigator.of(context).push(
                MaterialPageRoute(
                  builder:
                      (BuildContext context) =>
                          DiscoverChildPage(title: '添加朋友'),
                ),
              );
            },
            child: Container(
              margin: EdgeInsets.only(right: 10),
              child: Image(
                image: AssetImage('assets/images/icon_friends_add.png'),
                width: 25,
              ),
            ),
          ),
        ],
        backgroundColor: WeChatThemeColor,
        title: Text('通讯录'),
      ),
      body: Stack(
        children: [
          Container(
            color: WeChatThemeColor,
            child: ListView.builder(
              controller: _scrollController,
              itemBuilder: _itemForRow,
              itemCount: _listDatas.length + _headerData.length,
            ),
          ),
          IndexBar(
            indexBarCallBack: (String str) {
              if (_groupOffsetMap[str] != null) {
                _scrollController.animateTo(
                  _groupOffsetMap[str],
                  duration: Duration(microseconds: 100),
                  curve: Curves.easeIn,
                );
              }
            },
          ), //列表
        ],
      ),
    );
  }

  Widget _itemForRow(BuildContext context, int index) {
    //显示头部4个Cell
    if (index < _headerData.length) {
      return _FriendCell(
        imageAssets: _headerData[index].imageAssets!,
        name: _headerData[index].name,
      );
    }
    //是否显示组名字！
    bool _hiddenIndexLetter =
        (index - 4 > 0 &&
            _listDatas[index - 4].indexLetter ==
                _listDatas[index - 5].indexLetter);

    return _FriendCell(
      imageUrl: _listDatas[index - 4].imageUrl,
      name: _listDatas[index - 4].name,
      groupTitle: _hiddenIndexLetter ? null : _listDatas[index - 4].indexLetter,
    );
  }
}

class _FriendCell extends StatelessWidget {
  const _FriendCell({
    this.imageUrl,
    required this.name,
    this.groupTitle,
    this.imageAssets,
  });

  final String? imageUrl;
  final String name;
  final String? groupTitle;
  final String? imageAssets;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          alignment: Alignment.centerLeft,
          padding: EdgeInsets.only(left: 10),
          height: groupTitle != null ? 30 : 0,
          color: WeChatThemeColor,
          child:
              groupTitle != null
                  ? Text(groupTitle!, style: TextStyle(color: Colors.grey))
                  : null,
        ), //头部
        Container(
          color: Colors.white,
          child: Row(
            children: [
              Container(
                margin: EdgeInsets.all(10),
                width: 34,
                height: 34,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(6.0),
                  image: DecorationImage(
                    image:
                        imageUrl != null
                            ? NetworkImage(imageUrl!)
                            : AssetImage(imageAssets!),
                  ),
                ),
              ), //图片
              SizedBox(
                // color: Colors.red,
                width: screenWidth(context) - 54,
                child: Column(
                  children: [
                    Container(
                      alignment: Alignment.centerLeft,
                      height: 54,
                      child: Text(name, style: TextStyle(fontSize: 18)),
                    ),
                    Container(height: 0.5, color: WeChatThemeColor), //下划线
                  ],
                ),
              ), //昵称+下划线
            ],
          ),
        ), //Cell的内容
      ],
    );
  }
}

const INDEX_WORDS = [
  '🔍',
  '☆',
  'A',
  'B',
  'C',
  'D',
  'E',
  'F',
  'G',
  'H',
  'I',
  'J',
  'K',
  'L',
  'M',
  'N',
  'O',
  'P',
  'Q',
  'R',
  'S',
  'T',
  'U',
  'V',
  'W',
  'X',
  'Y',
  'Z',
];
